package com.retailcloud.searchservice.service.impl;

import com.alibaba.fastjson.JSON;
import com.retailcloud.commonutils.constant.EsConstant;
import com.retailcloud.commonutils.dto.ProductSearchVo;
import com.retailcloud.commonutils.dto.ProductionInfoVo;
import com.retailcloud.searchservice.service.ProductService;
import com.retailcloud.searchservice.utils.ElasticsearchClientUtil;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.xcontent.XContentType;

import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ProductServiceImpl implements ProductService {

    @Override
    public boolean productStatusUp(List<ProductionInfoVo> skuEsModels) throws IOException {
        // 保存到es中
        // 1、给es中建立索引。product， 建立好映射关系
        // 2、给es中保存这些数据 bulk 批量保存
        BulkRequest bulkRequest = new BulkRequest();
        for (ProductionInfoVo productionInfoVo : skuEsModels) {
            // 构建一个一个的保存请求
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            // 指定每个商品的id
            indexRequest.id(productionInfoVo.getId());
            // 每个商品的内容,Json
            String s = JSON.toJSONString(productionInfoVo);
            indexRequest.source(s, XContentType.JSON);
            // 把每一个保存请求都放在bulk请求中
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulk = ElasticsearchClientUtil.getClient().bulk(bulkRequest, RequestOptions.DEFAULT);
        // TODO 如果批量错误
        boolean b = bulk.hasFailures();
        List<String> collect = Arrays.stream(bulk.getItems()).map(item -> {
            return item.getId();
        }).collect(Collectors.toList());
        ElasticsearchClientUtil.closeClient();
        log.info("商品同步成功:{}", collect);
        return b;
    }

    @Override
    public Map<String, Object> getProductInfoList(ProductSearchVo productSearchVo) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            // 构建查询条件
            BoolQueryBuilder query = QueryBuilders.boolQuery();

            // 如果 keyword 不为空，则添加多字段匹配查询
            if (StringUtils.isNotBlank(productSearchVo.getKeyword())) {
                MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery(
                        productSearchVo.getKeyword(),
                        "productAttributes.attributeValue",
                        "name",
                        "fullAttributeValue",
                        "description"
                );
                query.must(multiMatchQueryBuilder);
            }

            if (StringUtils.isNotBlank(productSearchVo.getCategoryId())) {
                query.must(QueryBuilders.matchQuery("categoryId", productSearchVo.getCategoryId()));
            }
            query.must(QueryBuilders.matchQuery("tenantId", productSearchVo.getTenantId()));

            // 设置排序
            SortBuilder<?> sort = SortBuilders.fieldSort("id").order(SortOrder.ASC);

            // 设置分页参数
            int page = productSearchVo.getPageNum(); // 当前页码
            int size = productSearchVo.getPageSize(); // 每页大小
            String searchAfter = productSearchVo.getSearchAfter(); // 初始为空

            // 执行查询
            SearchResponse searchResponse = ElasticsearchClientUtil.searchWithPaging("retailcloud_product", query, sort, page, size, searchAfter);

            // 处理响应
            long totalHits = searchResponse.getHits().getTotalHits().value;

            List<Map<String, Object>> productionList = new ArrayList<>();
            for (var hit : searchResponse.getHits().getHits()) {
                Map<String, Object> sourceAsMap = hit.getSourceAsMap();
                productionList.add(sourceAsMap);
            }
            // 获取下一页的 search_after 值
            String nextSearchAfter = ElasticsearchClientUtil.getNextSearchAfter(searchResponse);

            resultMap.put("productionList", productionList);
            resultMap.put("total", totalHits);
            resultMap.put("nextSearchAfter", nextSearchAfter);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return resultMap;
    }
}
